package fr.imac.reader.database;

import fr.imac.reader.bean.Feed;
import fr.imac.reader.bean.Category;
import fr.imac.reader.bean.Unread;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ReaderDatabaseHelper extends SQLiteOpenHelper {
	
	private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "readers.db";
    
    /**
     * Table category
     */
    public static final String CATEGORY_TABLE_NAME = "category_table";
    private static final String CATEGORY_TABLE_CREATE =
        "CREATE TABLE " + CATEGORY_TABLE_NAME + " (" +
        Category.Columns._ID +" INTEGER PRIMARY KEY, "+
        Category.Columns.NAME + " TEXT, " +
        Category.Columns.PARENT_ID + " INTEGER,"+
        "FOREIGN KEY("+Category.Columns.PARENT_ID+") REFERENCES "+CATEGORY_TABLE_NAME+"("+Category.Columns._ID+")on delete cascade);";
            
    
    /**
     * Table Feed
     */
    public static final String FEED_TABLE_NAME = "feed_table";
    private static final String FEED_TABLE_CREATE =
        "CREATE TABLE " + FEED_TABLE_NAME + " (" +
        Feed.Columns._ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+
        Feed.Columns.NAME + " TEXT, " +
        Feed.Columns.URL + " TEXT, " +
        Feed.Columns.UPDATE_DATE + " INTEGER, " +
        Feed.Columns.UPDATE_STATUS + " INTEGER, " +
        Feed.Columns.CATEGORY_ID + " INTEGER, "+
        "FOREIGN KEY("+Feed.Columns.CATEGORY_ID+") REFERENCES "+CATEGORY_TABLE_NAME+"("+Category.Columns._ID+")on delete cascade);";
         
    
    /**
     * Table Unread
     */
    public static final String UNREAD_TABLE_NAME = "unread_table";
    private static final String UNREAD_TABLE_CREATE =
        "CREATE TABLE " + UNREAD_TABLE_NAME + " (" +
        Unread.Columns._ID+" INTEGER PRIMARY KEY,"+
        Unread.Columns.URL + " TEXT, " +
        Unread.Columns.PUB_DATE + " TEXT, " +
        Unread.Columns.FEED_ID + " INTEGER"+");";
       
    ReaderDatabaseHelper(Context context) 
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    	db.execSQL(CATEGORY_TABLE_CREATE);
    	db.execSQL(FEED_TABLE_CREATE);
        db.execSQL(UNREAD_TABLE_CREATE);
    }
    
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        db.execSQL("DROP TABLE IF EXISTS "+CATEGORY_TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS "+FEED_TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS "+UNREAD_TABLE_NAME);
        onCreate(db);
    }
    

}
